package database

import (
	"database/sql"
	"encoding/json"
	"fmt"
	"time"
)

// SessionStatus 会话状态枚举
type SessionStatus string

const (
	StatusWaiting      SessionStatus = "waiting"
	StatusConnected    SessionStatus = "connected"
	StatusDisconnected SessionStatus = "disconnected"
	StatusEnded        SessionStatus = "ended"
)

// SessionType 会话类型枚举
type SessionType string

const (
	TypeLive   SessionType = "live"
	TypeReplay SessionType = "replay"
)

// QualityLevel 视频质量枚举
type QualityLevel string

const (
	Quality480p  QualityLevel = "480p"
	Quality720p  QualityLevel = "720p"
	Quality1080p QualityLevel = "1080p"
)

// VideoSession 视频会话模型
type VideoSession struct {
	SessionID    string          `json:"session_id"`
	OrderID      string          `json:"order_id"`
	RoomID       string          `json:"room_id"`
	CustomerID   uint64          `json:"customer_id"`
	ProviderID   uint64          `json:"provider_id"`
	SessionType  SessionType     `json:"session_type"`
	Status       SessionStatus   `json:"status"`
	StartTime    *time.Time      `json:"start_time"`
	EndTime      *time.Time      `json:"end_time"`
	Duration     uint            `json:"duration"`
	QualityLevel QualityLevel    `json:"quality_level"`
	IsRecorded   bool            `json:"is_recorded"`
	RecordingURL string          `json:"recording_url"`
	RecordingSize uint64         `json:"recording_size"`
	Participants json.RawMessage `json:"participants"`
	CreatedAt    time.Time       `json:"created_at"`
	UpdatedAt    time.Time       `json:"updated_at"`
}

// GetVideoSessionByID 通过会话ID获取视频会话
func GetVideoSessionByID(sessionID string) (*VideoSession, error) {
	if DB == nil {
		return nil, fmt.Errorf("数据库未初始化")
	}

	query := `SELECT session_id, order_id, room_id, customer_id, provider_id, 
			session_type, status, start_time, end_time, duration, 
			quality_level, is_recorded, recording_url, recording_size, 
			participants, created_at, updated_at 
			FROM video_sessions WHERE session_id = ? LIMIT 1`

	var session VideoSession
	var startTime, endTime sql.NullTime
	var participants sql.NullString
	
	err := DB.QueryRow(query, sessionID).Scan(
		&session.SessionID,
		&session.OrderID,
		&session.RoomID,
		&session.CustomerID,
		&session.ProviderID,
		&session.SessionType,
		&session.Status,
		&startTime,
		&endTime,
		&session.Duration,
		&session.QualityLevel,
		&session.IsRecorded,
		&session.RecordingURL,
		&session.RecordingSize,
		&participants,
		&session.CreatedAt,
		&session.UpdatedAt,
	)

	if err != nil {
		if err == sql.ErrNoRows {
			return nil, nil // 没有找到记录
		}
		return nil, fmt.Errorf("查询视频会话失败: %v", err)
	}

	// 处理可空字段
	if startTime.Valid {
		session.StartTime = &startTime.Time
	}
	if endTime.Valid {
		session.EndTime = &endTime.Time
	}
	if participants.Valid {
		session.Participants = json.RawMessage(participants.String)
	}

	return &session, nil
}

// GetVideoSessionByRoomID 通过房间ID获取视频会话
func GetVideoSessionByRoomID(roomID string) (*VideoSession, error) {
	if DB == nil {
		return nil, fmt.Errorf("数据库未初始化")
	}

	query := `SELECT session_id, order_id, room_id, customer_id, provider_id, 
			session_type, status, start_time, end_time, duration, 
			quality_level, is_recorded, recording_url, recording_size, 
			participants, created_at, updated_at 
			FROM video_sessions WHERE room_id = ? LIMIT 1`

	var session VideoSession
	var startTime, endTime sql.NullTime
	var participants sql.NullString
	
	err := DB.QueryRow(query, roomID).Scan(
		&session.SessionID,
		&session.OrderID,
		&session.RoomID,
		&session.CustomerID,
		&session.ProviderID,
		&session.SessionType,
		&session.Status,
		&startTime,
		&endTime,
		&session.Duration,
		&session.QualityLevel,
		&session.IsRecorded,
		&session.RecordingURL,
		&session.RecordingSize,
		&participants,
		&session.CreatedAt,
		&session.UpdatedAt,
	)

	if err != nil {
		if err == sql.ErrNoRows {
			return nil, nil // 没有找到记录
		}
		return nil, fmt.Errorf("查询视频会话失败: %v", err)
	}

	// 处理可空字段
	if startTime.Valid {
		session.StartTime = &startTime.Time
	}
	if endTime.Valid {
		session.EndTime = &endTime.Time
	}
	if participants.Valid {
		session.Participants = json.RawMessage(participants.String)
	}

	return &session, nil
}

// GetVideoSessionByOrderID 通过订单ID获取视频会话
func GetVideoSessionByOrderID(orderID string) (*VideoSession, error) {
	if DB == nil {
		return nil, fmt.Errorf("数据库未初始化")
	}

	query := `SELECT session_id, order_id, room_id, customer_id, provider_id, 
			session_type, status, start_time, end_time, duration, 
			quality_level, is_recorded, recording_url, recording_size, 
			participants, created_at, updated_at 
			FROM video_sessions WHERE order_id = ? LIMIT 1`

	var session VideoSession
	var startTime, endTime sql.NullTime
	var participants sql.NullString
	
	err := DB.QueryRow(query, orderID).Scan(
		&session.SessionID,
		&session.OrderID,
		&session.RoomID,
		&session.CustomerID,
		&session.ProviderID,
		&session.SessionType,
		&session.Status,
		&startTime,
		&endTime,
		&session.Duration,
		&session.QualityLevel,
		&session.IsRecorded,
		&session.RecordingURL,
		&session.RecordingSize,
		&participants,
		&session.CreatedAt,
		&session.UpdatedAt,
	)

	if err != nil {
		if err == sql.ErrNoRows {
			return nil, nil // 没有找到记录
		}
		return nil, fmt.Errorf("查询视频会话失败: %v", err)
	}

	// 处理可空字段
	if startTime.Valid {
		session.StartTime = &startTime.Time
	}
	if endTime.Valid {
		session.EndTime = &endTime.Time
	}
	if participants.Valid {
		session.Participants = json.RawMessage(participants.String)
	}

	return &session, nil
}

// IsValidSession 检查会话是否有效
func IsValidSession(roomID string, userID uint64, isCustomer bool) (bool, error) {
	session, err := GetVideoSessionByRoomID(roomID)
	if err != nil {
		return false, err
	}

	// 会话不存在
	if session == nil {
		return false, nil
	}

	// 检查会话状态是否允许连接
	if session.Status == StatusEnded {
		return false, nil
	}

	// 检查用户ID是否匹配（根据用户类型检查不同的字段）
	if isCustomer {
		if session.CustomerID != userID {
			return false, nil
		}
	} else {
		if session.ProviderID != userID {
			return false, nil
		}
	}

	return true, nil
}

// UpdateSessionStatus 更新会话状态
func UpdateSessionStatus(sessionID string, status SessionStatus) error {
	if DB == nil {
		return fmt.Errorf("数据库未初始化")
	}

	query := `UPDATE video_sessions SET status = ? WHERE session_id = ?`
	_, err := DB.Exec(query, status, sessionID)
	if err != nil {
		return fmt.Errorf("更新会话状态失败: %v", err)
	}

	return nil
}

// UpdateSessionStartTime 更新会话开始时间
func UpdateSessionStartTime(sessionID string) error {
	if DB == nil {
		return fmt.Errorf("数据库未初始化")
	}

	query := `UPDATE video_sessions SET start_time = CURRENT_TIMESTAMP, status = ? WHERE session_id = ?`
	_, err := DB.Exec(query, StatusConnected, sessionID)
	if err != nil {
		return fmt.Errorf("更新会话开始时间失败: %v", err)
	}

	return nil
}

// UpdateSessionEndTime 更新会话结束时间和持续时间
func UpdateSessionEndTime(sessionID string) error {
	if DB == nil {
		return fmt.Errorf("数据库未初始化")
	}

	// 更新结束时间并计算持续时间（秒）
	query := `UPDATE video_sessions 
			SET end_time = CURRENT_TIMESTAMP, 
			status = ?, 
			duration = TIMESTAMPDIFF(SECOND, start_time, CURRENT_TIMESTAMP) 
			WHERE session_id = ?`
	
	_, err := DB.Exec(query, StatusEnded, sessionID)
	if err != nil {
		return fmt.Errorf("更新会话结束时间失败: %v", err)
	}

	return nil
}